﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace TestAttribute
{
    static class MsgCollectionHelper
    {
        /// <summary>
        /// 对象和消息映射
        /// </summary>
        public struct MsgSender
        {
            public Type sender;
            public MethodInfo methodInfo;
            public MsgSender(MethodInfo _methodInfo,Type _sender)
            {
                methodInfo = _methodInfo;
                sender = _sender;
            }
        }

        //消息ID和方法注册到字典
        public static Dictionary<int, MsgSender> msgDic = new Dictionary<int, MsgSender>();

        static List<Type> classType = new List<Type>()
        {
            typeof(MessageCenter)
            //TODO:此处添加网络消息类
        };
        

        /// <summary>
        /// 反射收集方法
        /// </summary>
        public static void CollectMsgFuncation()
        {
            Console.WriteLine("-----------------------------开始收集方法---------------------------------");
            for (int i = 0; i < classType.Count; i++)
            {
                foreach (MethodInfo info in classType[i].GetMethods())
                {
                    foreach (Attribute attribute in Attribute.GetCustomAttributes(info))
                    {
                        if (attribute.GetType() == typeof(TestAttribute.Execute))
                        {
                            Console.WriteLine("Method [{0}] has a execute [{1}] attribute,msgID:{2}",
                                info.Name, ((Execute)attribute), ((Execute)attribute).MsgID);
                            msgDic.Add(((Execute)attribute).MsgID,new MsgSender(info,classType[i]));
                        }
                    }
                }
            }
            Console.WriteLine("-----------------------------收集方法结束---------------------------------");
        }
    }
}
